/*
 * $Id$
 *
 * Copyright 2008 HuangHuang. All rights reserved.
 */
package com.crm.web.page;

import org.apache.tapestry.html.BasePage;
import org.apache.tapestry.valid.ValidationConstraint;
import org.apache.tapestry.valid.ValidationDelegate;
import org.apache.tapestry.annotations.Bean;
import org.apache.tapestry.annotations.InjectState;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.javaforge.tapestry.spring.annotations.InjectSpring;
import com.crm.service.IUserService;
import com.crm.service.utils.MsgDigest;
import com.crm.model.User;

/**
 * @author <a href="mailto:huang0510@hotmail.com">HuangHuang</a>
 * @version $Id$
 */
public abstract class SysModifyPassword extends BasePage {
    
    private static Log log = LogFactory.getLog(SysModifyPassword.class);

    @Bean
    public abstract ValidationDelegate getDelegate();

    @InjectSpring("userService")
    public abstract IUserService getUserService();

    @InjectState("userSession")
    public abstract User getUserSession();

    public abstract String getOldPassword();
    public abstract String getNewPassword();
    public abstract String getConfirmPassword();

    public String infoSubmit(){
        try{
            if(getDelegate().getHasErrors()){
                return getPageName();
            }

            User user = getUserSession();
            String oldPwd = user.getPassword();
            if(oldPwd==null) return "SysPageError";
            if(!MsgDigest.getSHA(getOldPassword()).equals(oldPwd)){
                String message = "您输入的旧密码不正确！";
                getDelegate().record(message, ValidationConstraint.CONSISTENCY);
                return getPageName();
            }

            if(!getNewPassword().equals(getConfirmPassword())){
                String message = "两次新密码不一致！";
                getDelegate().record(message, ValidationConstraint.CONSISTENCY);
                return getPageName();
            }

            user.setPassword(MsgDigest.getSHA(getNewPassword()));
            getUserService().alterUser(user);

            log.info(user.getUsername() + " : password modify success!");
            String message = "密码修改成功，请使用新密码登录系统！";
            getDelegate().record(message, ValidationConstraint.CONSISTENCY);
            return "SysModifyPassword";
        }
        catch(Exception e){
            log.error(getUserSession().getUsername() + " : The error happened when modify password.");
            String message = "保存数据时发生异常： " + e.getMessage();
            getDelegate().record(message, ValidationConstraint.CONSISTENCY);
            e.printStackTrace();
            return getPageName();
        }


    }
}
